const Router = require('koa-router')
const goods = new Router()
const query = require('../util/db')

// 获取所有商品数据
// http://127.0.0.1:8080/goods/all
goods.get('/all',async ctx => {
    let sql = `select * from goods`
    let result = await query(sql)
    if(result.length === 0){
        ctx.body = {
            code: 201,
            msg: '未查询到相关数据'
        }
        return
    }
    ctx.body ={
        code: 200,
        msg: '查询成功',
        data: result
    }
})

//根据种类id查询商品数据并限制条数，默认100
//http://127.0.0.1:8080/goods/kind?gid=1&count=100
goods.get('/kind',async ctx => {
    let gid = ctx.request.query.gid
    let count = ctx.request.query.count
    let sql = `select * from goods where gsideid = ? limit ?`
    let result = await query(sql,[gid,parseInt(count)])
    if(result.length === 0){
        ctx.body = {
            code: 201,
            msg: '未查询到相关信息'
        }
        return
    }
    ctx.body = {
        code: 200,
        msg: '查询成功',
        data: result
    }
})

//根据种类id查询商品数据并限制条数，默认100,并且按照价格升序排列
//http://127.0.0.1:8080/goods/priceup?gid=1&count=100
goods.get('/priceup',async ctx => {
    let gid = ctx.request.query.gid
    let count = ctx.request.query.count
    let sql = `select * from goods where gsideid = ? order by gprice limit ?`
    let result = await query(sql,[gid,parseInt(count)])
    if(result.length === 0){
        ctx.body = {
            code: 201,
            msg: '未查询到相关信息'
        }
        return
    }
    ctx.body = {
        code: 200,
        msg: '查询成功',
        data: result
    }
})

//根据种类id查询商品数据并限制条数，默认100,并且按照价格降序排列
//http://127.0.0.1:8080/goods/pricedown?gid=1&count=100
goods.get('/pricedown',async ctx => {
    let gid = ctx.request.query.gid
    let count = ctx.request.query.count
    let sql = `select * from goods where gsideid = ? order by gprice desc  limit ?`
    let result = await query(sql,[gid,parseInt(count)])
    if(result.length === 0){
        ctx.body = {
            code: 201,
            msg: '未查询到相关信息'
        }
        return
    }
    ctx.body = {
        code: 200,
        msg: '查询成功',
        data: result
    }
})

// 根据商品id查询该商品的数据
//http://127.0.0.1:8080/goods/searchone?gid=1
goods.get('/searchone',async ctx => {
    let gid = ctx.request.query.gid
    let sql = `select * from goods where gid = ?`
    let result = await query(sql,[gid])
    if(result.length === 0){
        ctx.body = {
            code: 201,
            msg: '未查询到该商品'
        }
        return
    }
    result[0].gimg = result[0].gimg.split(',');
    result[0].gcolor = result[0].gcolor.split(',');
    ctx.body = {
        code: 200,
        msg: '查询商品成功',
        data: result[0]
    }
})
module.exports = goods